package com.up.vms.interfaces.rest.component;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.processing.OperationStatus;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class QnOssManager {

    @Value("${vms.qiniu.accessKey}")
    private String accessKey;

    @Value("${vms.qiniu.secretKey}")
    private String secretKey;

    @Value("${vms.qiniu.image.url}")
    private String ServerPath;

    @Value("${vms.qiniu.temp.url}")
    private String ServerPathTemp;

    @Value("${vms.qiniu.video.url}")
    private String ServerPathVideo;

    @Value("${vms.qiniu.image.bucket}")
    private String imageBucket;
    @Value("${vms.qiniu.temp.bucket}")
    private String tempBucket;
    @Value("${vms.qiniu.video.bucket}")
    private String vidoeBucket;
    @Value("${vms.qiniu.video.mp4pipe}")
    private String mp4pipe;
    @Value("${soft.domain}")
    private String softDomain;

    public int getFileType(String originalFilename) {

        String suffix = originalFilename.substring( originalFilename.lastIndexOf( "." ) ).toLowerCase();

        return 0;
    }

    public String upToken(String bucket) {

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, null, 60*60*24L, null);

        return upToken;
    }

    public Map<String, Object> saveFileToQiniu(InputStream inputStream, int fileType, String originalFileName, String fileTypeStr, Object o) throws Exception {

        Map<String, Object> map = new HashMap<>();

        Configuration cfg = new Configuration(Region.region0());

        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传

        String bucket = imageBucket;
        String retPath = ServerPath;

        if (fileType == 1) {
            bucket = tempBucket;
            retPath = ServerPathTemp;
        }

        ////如果是Windows情况下，格式是 D:\\qiniu\\test.pngF:\Downloads
        //        String localFilePath = "F:\\Downloads\\bg_001.jpg";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            log.info("up to qiniu");
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
            log.info("key=" + putRet.key);

            retPath = retPath + putRet.key;
            map.put("key", putRet.key);
//            Map state = statFile(bucket, putRet.key);
//            map.put("fsize", state.get("fsize"));
//            map.put("mimeType", state.get("mimeType"));
        } catch (QiniuException ex) {
            retPath = "";
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
                throw new Exception(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

        map.put("fileUrl", retPath);

        return map;
    }

    public Map<String, Object> operateFile(String key) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Auth auth = Auth.create(accessKey, secretKey);
        String bucket = tempBucket;
//数据处理指令，支持多个指令
        String newBucket = vidoeBucket;
        String saveMp4Entry = String.format("%s:%s", newBucket, UUID.randomUUID() + ".mp4");
        String avthumbMp4Fop = String.format("avthumb/mp4|saveas/%s", UrlSafeBase64.encodeToString(saveMp4Entry));
        String persistentOpfs = StringUtils.join(new String[]{
                avthumbMp4Fop
        }, ";");

        //数据处理队列名称，必须
        String persistentPipeline = mp4pipe;
        //数据处理完成结果通知地址
        String persistentNotifyUrl = softDomain + "/vms/v1/video/pfop/notify";

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //构建持久化数据处理对象
        OperationManager operationManager = new OperationManager(auth, cfg);

        try {
            String persistentId = operationManager.pfop(bucket, key, persistentOpfs, persistentPipeline, persistentNotifyUrl, true);
            //可以根据该 persistentId 查询任务处理进度
            OperationStatus operationStatus = operationManager.prefop(persistentId);

            map.put("persistentId", persistentId);
            map.put("status", operationStatus);
            //解析 operationStatus 的结果
        } catch (QiniuException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
        return map;
    }

    public Map<String, Object> pfopStatus(String persistentId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Auth auth = Auth.create(accessKey, secretKey);
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //构建持久化数据处理对象
        OperationManager operationManager = new OperationManager(auth, cfg);

        try {
            OperationStatus operationStatus = operationManager.prefop(persistentId);

            map.put("persistentId", persistentId);
            map.put("url", ServerPathVideo + "/" + operationStatus.items[0].key);
            map.put("status", operationStatus);
            //解析 operationStatus 的结果
        } catch (QiniuException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
        return map;
    }


    public Map<String, Object> deleteFile(String bucket, String key) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Auth auth = Auth.create(accessKey, secretKey);
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //构建持久化数据处理对象
        BucketManager bucketManager = new BucketManager(auth, cfg);

        try {
            Response response = bucketManager.delete(bucket, key);
//解析上传成功的结果

//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
            map.put("result", response.bodyString());
        } catch (QiniuException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
        return map;
    }

    public Map<String, Object> statFile(String bucket, String key) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            FileInfo fileInfo = bucketManager.stat(bucket, key);
            map.put("key", fileInfo.key);
            map.put("fsize", fileInfo.fsize);
            map.put("mimeType", fileInfo.mimeType);
        } catch (QiniuException ex) {
            log.error(ex.getMessage(), ex);
        }
        return map;
    }
}
